﻿using System;

namespace Com.PhilChuang.Pmvp.Utils
{
	/// <summary>
	/// Helper class for app lifecycle
	/// </summary>
	public interface IAppHelper
	{
		event Action<Object, HandledEventArgs<Exception>> UnhandledException;
		event Action Launching;
		event Action Suspending;
		event Action Resuming;
		event Action Closing;

		AppLaunchStatus LaunchStatus { get; }
		AppStatus Status { get; }

		void ForceExit ();
	}

	public class DefaultAppHelper : IAppHelper
	{
		public event Action<Object, HandledEventArgs<Exception>> UnhandledException = delegate { };
		protected void FireUnhandledException (Object sender, HandledEventArgs<Exception> e)
		{
			foreach (var d in UnhandledException.GetInvocationList ())
			{
				d.DynamicInvoke (sender, e);
				if (e.Handled) return;
			}
		}
		public event Action Launching = delegate { };
		protected void FireLaunching () { Launching (); }
		public event Action Suspending = delegate { };
		protected void FireSuspending () { Suspending (); }
		public event Action Resuming = delegate { };
		protected void FireResuming () { Resuming (); }
		public event Action Closing = delegate { };
		protected void FireClosing () { Closing (); }

		public AppLaunchStatus LaunchStatus { get; protected set; }
		public AppStatus Status { get; protected set; }

		public virtual void OnUnhandledException (object sender, HandledEventArgs<Exception> e)
		{
			FireUnhandledException (sender, e);
		}

		public virtual void OnAppLaunch ()
		{
			Status = AppStatus.Launching;
			FireLaunching ();
			Status = AppStatus.Launched;
		}

		public virtual void OnAppSuspend ()
		{
			Status = AppStatus.Suspending;
			FireSuspending ();
			Status = AppStatus.Suspended;
		}

		public virtual void OnAppResume ()
		{
			Status = AppStatus.Resuming;
			FireResuming ();
			Status = AppStatus.Resumed;
		}

		public virtual void OnAppClose ()
		{
			Status = AppStatus.Closing;
			FireClosing ();
			Status = AppStatus.Closed;
		}

		public virtual void ForceExit ()
		{
			throw new NotImplementedException ();
		}
	}

	public enum AppLaunchStatus
	{
		IsFresh,
		IsResume,
	}

	public enum AppStatus
	{
		Launching,
		Launched,
		Suspending,
		Suspended,
		Resuming,
		Resumed,
		Closing,
		Closed,
	}
}
